import Https from "@/utils/Https";
import { passWordReg, passWordRegMessage } from "@/utils/regExp";
import { Button, Form, Input, message, Modal, Space, Spin, Tag } from "antd";
import { FC, useEffect, useState } from "react";
import { removeItem } from "@/utils/localstorage";
import { TOKEN } from "@/constants";
import styles from "../index.less";
const Security: FC<{}> = () => {
  const [loading, setLoading] = useState(false);
  const [userInfo, setUserInfo] = useState({});
  const [open, setOpen] = useState(false);
  const [telOpen, setTelOpen] = useState(false);
  const [btnStatus, setBtnStatus] = useState(false);
  const [count, setCount] = useState(60);
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const { confirm } = Modal;
  const telFun = (tel) => {
    tel = "" + tel;
    var tel1 = tel.replace(tel.substring(3, 7), "****");
    return tel1;
  };
  const getDetails = async () => {
    setLoading(true);
    let res: any = await Https.get("/user/profile", {}, true);
    setLoading(false);
    if (res.code == 200) {
      setUserInfo(res.data.user);
    } else {
      message.error(res.msg);
    }
  };
  //提交密码
  const submitPass = async () => {
    let result = await form.validateFields();
    if (result.newPassword != result.confirmPassword) {
      message.error("重复密码与新密码不一致");
      return;
    }
    setLoading(true);
    let res: any = await Https.put("/user/profile/updatePwd", result, true);
    setLoading(false);
    if (res.code == 200) {
      setOpen(false);
      confirm({
        title: "提示",
        icon: null,
        content: "密码修改成功,请重新登录",
        onOk() {
          removeItem(TOKEN);
          window.location.reload();
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    } else {
      message.error(res.msg);
    }
  };
  //获取验证码
  const sendSms = async () => {
    setBtnStatus(true);
    let newCount = count;
    let timer = setInterval(() => {
      if (newCount > 0) {
        setCount(newCount--);
      } else {
        setCount(60);
        setBtnStatus(false);
        clearInterval(timer);
      }
    }, 1000);
    let res: any = await Https.get("/user/profile/sendSms", {}, true);
    if (res && res.code == 200) {
      message.success("已发送验证码");
    } else {
      message.error(res.msg);
    }
  };
  //验证手机号
  const submitTel = async () => {
    let result = await form1.validateFields();
    setLoading(true);
    let res = await Https.get(
      "/user/profile/validateSmsCode",
      { code: result.code },
      true
    );
    setLoading(false);
    if (res && res.code == 200) {
      message.success("验证成功");
      getDetails();
      setTelOpen(false);
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    getDetails();
  }, []);
  return (
    <Spin spinning={loading}>
      <div className={styles.Security}>
        <div className={styles.title}>安全设置</div>
        <div className={styles.securityContent}>
          <div className={styles.securityList}>
            <div>
              <p>账户密码</p>
              <span className={styles.tips}>已设置账户密码</span>
            </div>
            <div>
              <a
                onClick={() => {
                  setOpen(true);
                  form.resetFields();
                }}
              >
                修改
              </a>
            </div>
          </div>
          <div className={styles.securityList}>
            <div>
              <p>手机号</p>
              <span className={styles.tips}>
                已绑定手机：
                <span
                  style={{ color: userInfo.phoneValidated ? "#55acee" : "" }}
                >
                  {userInfo.phonenumber && telFun(userInfo.phonenumber)}
                </span>
              </span>
              {!userInfo.phoneValidated ? (
                <Tag>未验证</Tag>
              ) : (
                <Tag color="#55acee">已验证</Tag>
              )}
            </div>
            <div>
              {!userInfo.phoneValidated && (
                <a
                  onClick={() => {
                    setTelOpen(true);
                    form1.resetFields();
                    form1.setFieldsValue({ phone: userInfo.phonenumber });
                  }}
                >
                  验证
                </a>
              )}
            </div>
          </div>
        </div>
      </div>
      <Modal
        open={open}
        title={"修改密码"}
        forceRender
        width="60%"
        destroyOnClose={true}
        onCancel={() => {
          setOpen(!open);
        }}
        footer={
          <Space>
            <Button
              onClick={() => {
                setOpen(false);
              }}
            >
              取消
            </Button>
            <Button
              onClick={() => {
                submitPass();
              }}
              loading={loading}
              type="primary"
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }}>
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[{ required: true }]}
          >
            <Input.Password placeholder="请输入" />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true },
              { pattern: passWordReg, message: passWordRegMessage },
            ]}
          >
            <Input.Password placeholder="6-12位包含数字、字母英文符号" />
          </Form.Item>
          <Form.Item
            label="重复密码"
            name="confirmPassword"
            rules={[{ required: true }]}
          >
            <Input.Password placeholder="6-12位包含数字、字母英文符号" />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        open={telOpen}
        title={"手机号验证"}
        forceRender
        width="60%"
        destroyOnClose={true}
        onCancel={() => {
          setTelOpen(false);
        }}
        footer={
          <Space>
            <Button
              onClick={() => {
                setTelOpen(false);
              }}
            >
              取消
            </Button>
            <Button
              onClick={() => {
                submitTel();
              }}
              loading={loading}
              type="primary"
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form1} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }}>
          <Form.Item label="手机号" name="phone" rules={[{ required: true }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="验证码"
            name="code"
            rules={[{ required: true }]}
            style={{ display: "inline-block", marginLeft: "63px" }}
          >
            <Input
              placeholder="请输入"
              style={{ width: "480px", marginRight: "40px" }}
            />
          </Form.Item>
          <Button
            style={{ marginLeft: "10px", width: "100px" }}
            disabled={btnStatus}
            onClick={() => {
              sendSms();
            }}
          >
            {!btnStatus ? "获取验证码" : count + "s"}
          </Button>
        </Form>
      </Modal>
    </Spin>
  );
};
export default Security;
